<template>
  <div>
    <el-row type="flex" justify="center">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span style="font-size: 18px; font-weight: bold;">创建集群</span>
          </div>
          <el-form ref="form" :model="form" label-width="150px" :rules="rules" @submit.native.prevent="submitForm">

            <!-- 集群名称 -->
            <el-form-item label="集群名称" prop="clusterName">
              <el-input v-model="form.clusterName" placeholder="请输入集群名称"></el-input>
            </el-form-item>

            <!-- 节点安装选项 -->
            <div class="section-title">节点安装选项(可选)</div>

            <el-form-item label="默认SSH登录方式" class="install-option">
              <el-button type="text" @click="openSelectAuthDialog">[选择已有认证]</el-button>
              <el-button type="text" @click="openAddAuthDialog">[添加新认证]</el-button>
              <span class="help-text">当前集群下节点统一的登录设置；当节点没有单独设置SSH登录方式时，默认使用此设置。</span>
            </el-form-item>

            <el-form-item label="节点安装目录" class="install-option">
              <el-input v-model="form.nodeInstallDirectory" placeholder="请输入安装目录"></el-input>
              <span class="help-text">当节点没有单独设置安装目录时，默认使用此设置。如果集群和节点都没有设置安装目录，则使用$登录用户HOME路径/edge-node 目录。</span>
            </el-form-item>

            <el-form-item label="自动安装nftables" class="install-option">
              <el-checkbox v-model="form.autoInstallNftables">自动安装nftables</el-checkbox>
              <span class="help-text">选中后,表示在Linux系统中自动尝试安装nftables用于安全防御;此功能需要联网从Ubuntu、CentOS等软件库中下载安装包</span>
            </el-form-item>

            <el-form-item label="自动调节系统参数" class="install-option">
              <el-checkbox v-model="form.autoTuneSystemParams">自动调节系统参数</el-checkbox>
              <span class="help-text">选中后,表示自动调整Linux内核等参数,以便提升性能。</span>
            </el-form-item>

            <!-- DNS设置选项 -->
            <div class="section-title">DNS设置选项(可选)</div>
            <el-form-item label="选择主域名" class="mainDomain">
              <el-button type="text" @click="openSelectMainDomainDialog">[选择域名]</el-button>
              <span class="help-text">用于生成集群节点和网站的CNAME和DNS解析记录</span>
            </el-form-item>
            <el-form-item label="DNS子域名" class="dns-option">
              <el-input v-model="form.dnsSubdomain" placeholder="请输入子域名">
                <template slot="append">.{{ mainDomain }}</template>
              </el-input>
              <span class="help-text">当前集群的子域名，和主域名一起组成集群节点的子域名。</span>
            </el-form-item>

            <el-form-item label="解析记录TTL(秒)" class="dns-option">
              <el-input-number v-model="form.dnsRecordTtl" :min="0"></el-input-number>
              <span class="unit"> 秒</span>
              <span class="help-text">生成解析记录时使用的TTL；每个DNS服务商或者套餐、账号限制各有不同，请注意允许的取值范围。0表示使用默认。</span>
            </el-form-item>

            <!-- 提交按钮 -->
            <el-form-item>
              <el-button type="primary" @click="submitForm">提交</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 选择已有认证对话框 -->
    <el-dialog title="选择已有认证" :visible.sync="selectAuthDialogVisible" width="50%">
      <el-input v-model="searchQuery" placeholder="输入认证名称或SSH用户名进行搜索" @input="searchAuth" style="width: 200px"></el-input>
      <el-table :data="filteredAuthList" stripe @row-click="handleRowClick">
        <el-table-column label="" width="40" align="left">
          <template slot-scope="scope" style="width: auto">
            <el-radio
              v-model="selectedAuth"
              :label="scope.row"
              class="radio"
              :disabled="selectedAuth && selectedAuth !== scope.row"
            />
          </template>
        </el-table-column>
        <el-table-column prop="sshName" label="认证名称" width="auto"></el-table-column>
        <el-table-column prop="sshUser" label="SSH用户名" width="auto"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
      <el-button @click="selectAuthDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="selectAuthConfirm">确定</el-button>
    </span>
    </el-dialog>

    <!-- 添加新认证对话框 -->
    <el-dialog title="添加新认证" :visible.sync="addAuthDialogVisible" width="50%">
      <!-- 表单内容 -->
      <el-form ref="authForm" :model="authForm" :rules="rules" label-width="150px" @submit.native.prevent="submitForm">
        <el-form-item label="名称" prop="sshName">
          <el-input v-model="authForm.sshName"></el-input>
          <span class="help-text">为当前认证信息起一个容易识别的名称</span>
        </el-form-item>
        <!-- 认证方式 -->
        <el-form-item label="认证方式">
          <el-select v-model="authForm.sshType">
            <el-option
              v-for="dict in dict.type.edge_nodes_ssh_type"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"
            />
          </el-select>

        </el-form-item>
        <el-form-item label="SSH用户名" prop="sshUser">
          <el-input v-model="authForm.sshUser"></el-input>
          <span class="help-text">SSH登录用户名。</span>
        </el-form-item>
        <el-form-item label="SSH密码" prop="sshKey" v-if="authForm.sshType==0">
          <el-input v-model="authForm.sshKey" type="password" show-password></el-input>
          <span class="help-text">SSH登录用户密码，为了安全起见，此项数据保存后将不允许在界面查看完整明文，为避免忘记，请自行记录原始数据。</span>
        </el-form-item>
        <el-form-item label="私钥" prop="sshKey" v-if="authForm.sshType==1">
          <el-input v-model="authForm.sshKey" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="备注" class="remark-form-item" prop="note">
          <el-collapse v-model="activeNames">
            <el-collapse-item title="点击展开备注" name="1">
              <el-input
                v-model="form.note"
                type="textarea"
                :rows="4"
              ></el-input>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAuthDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addAuthConfirm">确定</el-button>
      </span>
    </el-dialog>

    <!-- 选择集群DNS设置弹窗   -->
    <el-dialog title="选择集群DNS设置" :visible.sync="selectMainDomainDialogVisible" width="25%">
      <!-- 表单内容 -->
      <el-form ref="dnsProvidersForm" :model="dnsProvidersForm" :rules="rules" label-width="150px" @submit.native.prevent="submitForm">
        <!-- 服务商账号 -->
        <el-form-item label="DNS服务商" prop="providerType">
          <el-select v-model="dnsProvidersForm.providerType">
            <el-option
              v-for="dict in dict.type.edge_dns_providers"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <!-- 账号 -->
        <el-form-item label="账号">
          <el-select v-model="dnsProvidersForm.accountDescription">
            <el-option
              v-for="(account, index) in accountDescription"
              :key="account.value"
              :label="account.label"
              :value="account.value"
            />
          </el-select>
        </el-form-item>
        <!-- 域名 -->
        <el-form-item label="域名">
          <el-select v-model="dnsProvidersForm.domain">
            <el-option
              v-for="(domain, index) in domainList"
              :key="domain.value"
              :label="domain.label"
              :value="domain.value"
            />
          </el-select>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="selectMainDomainDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="selectMainDomainConfirm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {addSsh, listSsh} from '@/api/nodes/ssh';
import {addClusters} from "@/api/nodes/clusters";
import {getProvidersAccountList} from "@/api/dns/providers";

export default {
  dicts: ['edge_nodes_ssh_type','edge_dns_providers'],
  data() {
    return {
      form: {
        clusterName: '',
        nodeInstallDirectory: '',
        autoInstallNftables: false,
        autoTuneSystemParams: false,
        dnsSubdomain: '',
        dnsRecordTtl: 0,
        selectedAuthId: null,
        dnsDomain: ''
      },
      mainDomain: '主域名',
      selectAuthDialogVisible: false,
      addAuthDialogVisible: false,
      searchQuery: '',
      selectMainDomainDialogVisible:false,
      authForm: {},
      dnsProvidersForm:{
        providerType: '',
        accountDescription: null,
        domain:''
      },
      providerId:null,
      domainList:{},
      accountDescription: [],
      rules: {
        sshUser: [{ required: true, message: 'SSH用户名不能为空', trigger: 'blur' }],
        sshName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        clusterName: [{ required: true, message: '集群名称不能为空', trigger: 'blur' }],
      },
      filteredAuthList: [],
      authList: [],
      activeNames: [],
      selectedAuth: null,
    };
  },
  created() {

  },
  watch: {
    // 监听dnsProvidersForm.providerType的变化
    'dnsProvidersForm.providerType': function(newVal, oldVal) {
      if (newVal) {
        // 当服务商被选中时，调用方法查询账号
        this.fetchAccountsByProviderType(newVal);
      }
    }
  },
  methods: {
    // 根据DNS服务商获取所有服务商账号
    fetchAccountsByProviderType(providerType) {
      getProvidersAccountList(providerType)
        .then(response => {
          console.log(response,'response')
          if (response.data && response.data.length > 0) {
            this.accountDescription = response.data.map(account => ({
              value: account.id,
              label: account.accountDescription,
            }));

            if (response.data[0].domainList && response.data[0].domainList.length > 0) {
              this.domainList = response.data[0].domainList.map(domain => ({
                value: domain,
                label: domain,
              }));
            } else {
              this.domainList = [{ value: null, label: '没有域名可选' }];
            }
          } else {
            this.accountDescription = [{ value: null, label: '没有账号可选' }];
            this.domainList = [{ value: null, label: '没有域名可选' }];
          }
        })
        .catch(error => {
          // 处理错误情况
          this.accountDescription = [{ value: null, label: '加载账号失败' }];
          this.domainList = [{ value: null, label: '加载域名失败' }];
          console.error(error);
        });
    },
    // 选择域名确认键
    selectMainDomainConfirm(){
      this.providerId = this.dnsProvidersForm.accountDescription
      this.mainDomain = this.dnsProvidersForm.domain
      this.selectMainDomainDialogVisible = false
    },
    // 重置表单
    reset() {
      this.form = {
        clusterName: '',
        installDir: '',
        autoInstallNftables: false,
        autoTuneSystemParams: false,
        dnsSubdomain: '',
        dnsTtl: 0,
        selectedAuthId: null,
      };
      this.$refs.form.resetFields();
    },

    // 添加新认证表单重置
    authFormReset() {
      this.authForm = {
        sshName: '',
        sshType: 0,
        sshUser: 'root',
        sshKey: '',
        note: ''
      };
      this.$refs.authForm.resetFields();
    },

    // 重置搜索
    queryReset(){
      this.searchQuery= ''
    },

    // 提交表单
    submitForm() {
      if (this.form.selectedAuthId) {
        const submitForm = {
          ...this.form,
          autoInstallNftables: this.form.autoInstallNftables ? 1 : 0,
          autoTuneSystemParams: this.form.autoTuneSystemParams ? 1 : 0,
          dnsDomain: this.form.dnsSubdomain + '.' +this.mainDomain,
          providerId: this.providerId
        };
        addClusters(submitForm).then(response => {
          this.$message.success('集群创建成功！');
          this.reset();  // 提交成功后重置表单
          this.$router.go(-1)
        }).catch(error => {
          this.$message.error('创建集群失败，请稍后再试。');
        });
      } else {
        this.$message.error('请选择认证信息');
      }
    },

    // 打开选择已有认证对话框
    openSelectAuthDialog() {
      this.queryReset();
      this.selectAuthDialogVisible = true;
      this.fetchAuthList(); // 获取认证列表
    },

    // 获取认证列表
    fetchAuthList() {
      listSsh().then(response => {
          this.authList = response.rows;
          this.filteredAuthList = this.authList;
      })
    },

    // 打开选择域名对话框
    openSelectMainDomainDialog() {
      this.selectMainDomainDialogVisible = true;
    },

    // 搜索认证
    searchAuth() {
      if (this.searchQuery === '') {
        this.filteredAuthList = this.authList;
      } else {
        this.filteredAuthList = this.authList.filter(auth =>
          auth.sshName.includes(this.searchQuery) || auth.sshUser.includes(this.searchQuery)
        );
      }
    },

    openAddAuthDialog(){
      this.addAuthDialogVisible = true;
      this.authFormReset();
    },

    // 选择行
    handleRowClick(row) {
      if (this.selectedAuth === row) {
        this.selectedAuth = null;
        this.form.selectedAuthId = null;
      } else {
        // 选择新的认证
        this.selectedAuth = row;
        this.form.selectedAuthId = row.id;
      }
    },

    // 确认选择的认证
    selectAuthConfirm() {
      if (this.form.selectedAuthId) {
        this.$message.success('认证选择成功！');
        this.selectAuthDialogVisible = false;
      } else {
        this.$message.error('请选择一个认证信息。');
      }
    },

    // 添加新认证的确认操作
    addAuthConfirm() {
      // 提交表单
      this.$refs.authForm.validate((valid) => {
        if (valid) {
          // 表单验证通过，可以提交数据
          addSsh(this.authForm).then(response => {
            this.$message({
              type: 'success',
              message: '认证信息创建成功!'
            });
            this.addAuthDialogVisible = false
          }).catch(error => {
            this.$message({
              type: 'error',
              message: error.response.data.message || '创建认证信息失败，请稍后再试。'
            });
          });
        } else {
          // 表单验证失败
          console.log('表单验证失败');
          return false;
        }
      });
    }
  },
};
</script>

<style scoped>
.box-card {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px 0;
}

.install-option,
.dns-option {
  font-size: 14px;
}

.help-text {
  font-size: 12px;
  color: #888;
  margin-top: 5px;
  display: block;
}

.el-button {
  margin-left: 10px;
}

.dialog-footer {
  text-align: right;
}

.radio {
  margin-left: 10px;
}
</style>
